//
//  HZSListViewController.swift
//  私人通讯录
//
//  Created by 灿灿 on 2018/3/17.
//  Copyright © 2018年 HZSS. All rights reserved.
//

import UIKit

class HZSListViewController: UITableViewController {
    var personList = [Person]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        loadData { (list) in
            print(list)
            
            self.personList += list
            
            self.tableView.reloadData()
        }
    }
    
    // 模拟异步，利用闭包回调
    private func loadData(completion: @escaping (_ list: [Person]) -> ()) -> () {
        DispatchQueue.global().async {
            print("正在努力加载中...");
            
            Thread.sleep(forTimeInterval: 1);
            
            var arrayM = [Person]()
            
            for i in 0..<20 {
                let p = Person();
                
                p.name = "zhangsan - \(i)"
                p.phone = "10865" + String(format: "%06d", arc4random_uniform(100000))
                p.title = "boss"
                
                arrayM.append(p)
            }
            
            DispatchQueue.main.async {
                completion(arrayM)
            }
            
        }
    }
    
    @IBAction func newPerson(_ sender: Any) {
        performSegue(withIdentifier: "list2detail", sender: nil)
    }
    
    // MARK: - 控制器跳转方法
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! HZSDetailViewController
        
        // 设置选中的 Person
        // Swift 中 String 之外，绝大多数使用 as 需要 ? / !
        // as! / as? 直接根据前面的返回值来决定
        // 注意：if let / guard let 判空语句，一律使用 as?
        if let indexPath = sender as? IndexPath {
            vc.person = personList[indexPath.row]
            
            vc.completionCallBack = {
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        } else { // 新建联系人
            vc.completionCallBack = {
                guard let p = vc.person else {
                    return
                }
                
                self.personList.insert(p, at: 0)
                
                self.tableView.reloadData()
            }
        }
    }
    
    // MARK: - 代理方法
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        performSegue(withIdentifier: "list2detail", sender: indexPath)
    }
    
    // MARK: - 数据源方法
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        
        // Non-void function should return a value
//        guard let cell = realCell else {
//            return realCell!
//        }
        
        cell?.textLabel?.text = personList[indexPath.row].name
        cell?.detailTextLabel?.text = personList[indexPath.row].phone
        
        return cell!
    }

}
